package 多线程.三个线程实现顺序打印;

import java.util.concurrent.CountDownLatch;

/**
 * 场景：等待其他多个线程完成任务之后，主线程才能继续往下执行业务功能
 *
 * CountDownLatch的一个适用场景,就是用来进行多个线程的同步管理,线程调用了countDownLatch.await()之后
 * 需要等待countDownLatch的信号countDownLatch.countDown(),在收到信号前,它不会往下执行
 */
public class Test6 {
    /**
     * 构造方法的作用：
     * 构造一个用给定计数初始化为count的CountDownLatch
     * countDown()：使CountDownLatch初始值count减1
     * await()：调用此的线程会被挂起,它会等待直到count值为0才继续执行
     * 直到count减为0,当前调用await()方法的线程才继续执行
     */
    private static CountDownLatch countDownLatchB = new CountDownLatch(1);
    private static CountDownLatch countDownLatchC = new CountDownLatch(1);
    public static void main(String[] args) {
        Test6 t = new Test6();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                t.printA();
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

    public static void printA() {
        System.out.println("A");
        countDownLatchB.countDown();
    }

    public static void printB() throws InterruptedException {
        countDownLatchB.await();
        System.out.println("B");
        countDownLatchC.countDown();
    }

    public static void printC() throws InterruptedException {
        countDownLatchC.await();
        System.out.println("C");
    }
}
